import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sinosheets/main_config.dart';
import 'package:sinosheets/mixin/refresh_mixin.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/route/route_utils.dart';
import 'package:sinosheets/utils/bus_utils.dart';
import 'package:sinosheets/utils/lottie_utils.dart';
import 'package:sinosheets/utils/storage/LSUtil.dart';
import 'package:url_launcher/url_launcher.dart';

class ShoppingLogic extends GetxController with RefreshMixin {
  final TextEditingController searchController = TextEditingController();

  // 加载状态
  bool isLoading = true;

  // 分类图标数据
  List<Map<String, dynamic>> categoryIcons = [];

  bool isValidateCode = false;
  @override
  void onReady() {
    super.onReady();
    initData();
    bus.on('network_refresh', (value) {
      initData();
    });
    bus.on('code_update', (value) {
      initData();
    });
  }

  void initData() {
    isValidateCode = LSUtil.getInviteCode()['isValid'] ?? false;
    if (isValidateCode) {
      categoryIcons = [
        {
          'name': 'Free Gift',
          'icon': Icons.flash_on,
          'color': const Color(0xFFFF6B6B),
          'iconColor': Colors.white,
        },
        {
          'name': 'Shop',
          'icon': Icons.store,
          'color': const Color(0xFF45B7D1),
          'iconColor': Colors.white,
        },
        {
          'name': 'Category',
          'icon': Icons.category,
          'color': const Color.fromARGB(255, 202, 209, 69),
          'iconColor': Colors.white,
        },
      ];
    } else {
      categoryIcons = [];
    }
    onRefresh();
  }

  @override
  void onClose() {
    searchController.dispose();
    super.onClose();
  }

  @override
  Future<void> onRefresh() async {
    LottieUtils.showToastLoading();

    await loadData();
    super.onRefresh();
  }

  /// 加载数据
  Future<void> loadData() async {
    try {
      isLoading = true;
      update();
      if (isValidateCode) {
        await getIndexData();
      } else {
        await getNomalCategoryList();
        await getNomalProductPageList();
      }
    } catch (e) {
      print('加载数据失败: $e');
    } finally {
      isLoading = false;
      LottieUtils.hideToastLoading();
      update();
    }
  }

  /// 获取首页数据
  List zeroAndDiscountList = [];
  List shopList = [];
  List categoryList = [];
  List categoryProductList = [];

  ///一行双列图
  List doubleColumnImageList = [];

  ///商品美化图片
  List beautyProductList = [];

  ///其余商品
  List otherProductList = [];
  Future<void> getIndexData() async {
    BaseResponse response = await ProductApi.getIndexData();
    if (response.isSuccess) {
      Map<String, dynamic> data = response.data ?? {};
      zeroAndDiscountList = data['zeroAndDiscountList'] ?? [];
      shopList = data['shopList'] ?? [];
      categoryList = data['categoryList'] ?? [];
      categoryProductList = data['categoryProductList'] ?? [];
      if (isValidateCode) {
        ///取categoryProductList每个item的list数据，集合成一个list
        List allProductList = [];
        for (var item in categoryProductList) {
          allProductList.addAll(item['list'] ?? []);
        }
        //随机取两个作为双列图 剩下的随意取8个作为美化图  再剩下的作为其余商品
        doubleColumnImageList = allProductList.take(2).toList();
        beautyProductList = allProductList.skip(2).take(8).toList();
        otherProductList = allProductList.skip(10).toList();
      }
      update();
    }
  }

  ///获取普货分类
  Future<void> getNomalCategoryList() async {
    BaseResponse response = await ProductApi.getNomalCategoryList();
    if (response.isSuccess) {
      List list = response.data ?? [];
      //前5个
      categoryList = list.take(5).toList();
      update();
    }
  }

  ///获取普货商品列表
  Future<void> getNomalProductPageList() async {
    BaseResponse response = await ProductApi.getNomalProductPageList({
      'pageNum': 1,
      'pageSize': 40,
    });
    if (response.isSuccess) {
      List list = response.list ?? [];
      //随机取两个作为双列图 剩下的随意取8个作为美化图  再剩下的作为其余商品
      doubleColumnImageList = list.take(2).toList();
      beautyProductList = list.skip(2).take(8).toList();
      otherProductList = list.skip(10).toList();
      update();
    }
  }

  /// 搜索点击
  void onSearchClick() async {
    searchController.text = searchController.text.trim();
    if (searchController.text.isEmpty) {
      return;
    }

    ///判断是否包含链接
    if (hasLink(searchController.text)) {
      List<String> links = extractLinks(searchController.text);
      if (links.isNotEmpty) {
        //解析链接
        String link = links[0];
        BaseResponse response = await ProductApi.resolveUrl(link);
        if (response.isSuccess) {
          Map<String, dynamic> data = response.data ?? {};
          String url = data['url'] ?? '';
          launchUrl(Uri.parse('${AppPrefix.urlPrefix}/product-detail?url=${Uri.encodeComponent(url)}'));
        }
      }
      return;
    }

    RouteUtils.toSearch(keyword: searchController.text);
  }

  /// 分类点击
  void onCategoryTap(int index) {
    if (index == 0) {
      RouteUtils.toFreeGifts(zeroAndDiscountList);
    } else if (index == 1) {
      RouteUtils.toRecommendedShop(shopList);
    } else if (index == 2) {
      RouteUtils.toCategory();
    }
  }

  /// 商品点击
  void onProductTap(Map<String, dynamic> product) {
    String url = product['url'] ?? '';
    if (url.isNotEmpty) {
      launchUrl(Uri.parse('${AppPrefix.urlPrefix}/product-detail?url=${Uri.encodeComponent(url)}'));
    }
  }

  /// 更多商品点击
  void onMoreProductsTap() {
    Get.snackbar('提示', '更多商品功能开发中');
  }

  //判断内容中是否包含链接
  static bool hasLink(String content) {
    final RegExp linkRegExp = RegExp(r'(https?:\/\/|itaobuy:\/\/)[^\s]+');
    return linkRegExp.hasMatch(content);
  }

  //提取内容中的链接
  static List<String> extractLinks(String content) {
    final RegExp linkRegExp = RegExp(r'(https?:\/\/|itaobuy:\/\/)[^\s]+');
    Iterable<Match> matches = linkRegExp.allMatches(content);
    return matches.map((match) => match.group(0)!).toList();
  }
}
